package com.example.demo.config;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {

	@Override
	public void decide(Authentication arg0, Object arg1, Collection<ConfigAttribute> arg2)
			throws AccessDeniedException, InsufficientAuthenticationException {
		Iterator<ConfigAttribute> iterator = arg2.iterator();
		while (iterator.hasNext()) {
			ConfigAttribute cAttribute = iterator.next();
			String needRole = cAttribute.getAttribute();
			if ("ROLE_LOGIN".equals(needRole)) {
				if (arg0 instanceof AnonymousAuthenticationToken) {
					throw new BadCredentialsException("未登录");
				} else {
					return;
				}
			}
			Collection<? extends GrantedAuthority> authorities = arg0.getAuthorities();
			for (GrantedAuthority grantedAuthority : authorities) {
				if (grantedAuthority.getAuthority().equals(needRole)) {
					return;
				}
				
			}
		}
		throw new AccessDeniedException("权限不足！");
	}
	
	@Override
	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}
